package com.ty.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ty.dao.UserDao;
import com.ty.dao.impl.UserDaoImpl;
import com.ty.entity.User;
import com.ty.utils.PermissionUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/user/*")
public class UserServlet extends HttpServlet {
    private UserDao userDao = new UserDaoImpl();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/query":
                handleQuery(request, response);
                break;
            case "/delete":
                if (PermissionUtils.hasAdminPermission(request)) {
                    handleDelete(request, response);
                } else {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    response.getWriter().write("没有权限进行此操作");
                }
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }

        switch (pathInfo) {
            case "/query":
                handleQuery(request, response);
                break;
            case "/add":
                if (PermissionUtils.hasAdminPermission(request)) {
                    handleAdd(request, response);
                } else {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    response.getWriter().write("没有权限进行此操作");
                }
                break;
            case "/edit":
                if (PermissionUtils.hasAdminPermission(request)) {
                    handleEdit(request, response);
                } else {
                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
                    response.getWriter().write("没有权限进行此操作");
                }
                break;
            default:
                response.sendError(HttpServletResponse.SC_NOT_FOUND);
                break;
        }
    }

    // 其他方法保持不变


    private void handleQuery(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        String username = request.getParameter("username");
        List<User> users;
        
        if (username != null && !username.trim().isEmpty()) {
            users = userDao.findByUsername(username);
        } else {
            users = userDao.findAll();
        }

        StringBuilder html = new StringBuilder();
        for (User user : users) {
            html.append("<tr>")
                .append("<td>").append(user.getId()).append("</td>")
                .append("<td>").append(user.getUsername()).append("</td>")
                .append("<td>").append(user.getAccount()).append("</td>")
                .append("<td>").append("****").append("</td>")
                .append("<td>")
                .append("<a href='#' class='edit-link' data-id='").append(user.getId()).append("'>编辑</a> | ")
                .append("<a href='#' class='delete-link' data-id='").append(user.getId()).append("'>删除</a>")
                .append("</td>")
                .append("</tr>");
        }

        PrintWriter out = response.getWriter();
        out.write(html.toString());
    }

    private void handleAdd(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String account = username; // 使用用户名作为账号

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        user.setAccount(account);

        int result = userDao.add(user);
        
        PrintWriter out = response.getWriter();
        if (result > 0) {
            out.write("添加成功");
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("添加失败");
        }
    }

    private void handleEdit(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        String idStr = request.getParameter("id");
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        if (idStr == null || username == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("缺少必要参数");
            return;
        }

        User user = new User();
        user.setId(Integer.parseInt(idStr));
        user.setUsername(username);
        if (password != null && !password.trim().isEmpty()) {
            user.setPassword(password);
        }

        int result = userDao.update(user);
        
        PrintWriter out = response.getWriter();
        if (result > 0) {
            out.write("修改成功");
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("修改失败");
        }
    }

    private void handleDelete(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");

        String idStr = request.getParameter("id");
        if (idStr == null) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            response.getWriter().write("缺少ID参数");
            return;
        }

        int id = Integer.parseInt(idStr);
        int result = userDao.delete(id);
        
        PrintWriter out = response.getWriter();
        if (result > 0) {
            out.write("删除成功");
        } else {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.write("删除失败");
        }
    }
} 